import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { status } from 'nprogress'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    type: undefined
  }
}

// 私有的变量
const state = getDefaultState()

// setter方法
const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  // 账户类型(0代表后台用户，1代表商家)
  SET_TYPE: (state, type) => {
    state.type = type
  }
}

// 动作
const actions = {
  // user login
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      const postData = {
        loginName: userInfo.username.trim(),
        loginPwd: userInfo.password,
        code: userInfo.code,
        uuid: userInfo.uuid
      }

      login(postData).then(response => {
        const { data } = response
        // 放到 vuex的内存变量中
        commit('SET_TOKEN', data)
        // 还要把token放到 浏览器的cookie，防止用户刷新页面，token丢失的问题
        setToken(data)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        const { data } = response

        if (!data) {
          return reject('无效令牌，请重新登录.')
        }

        // 加载图片
        const headerImage = require('@/assets/header.png')

        commit('SET_NAME', data.accountVO.name)
        commit('SET_AVATAR', data.accountVO.avatar || headerImage)
        commit('SET_TYPE', data.accountVO.type)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout().then(() => {
        // 删除浏览器cookie中的令牌
        removeToken()
        // 重置路由
        resetRouter()
        // 重置vuex的变量的值
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
